package com.itheima.reggie.service.impl;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapping;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapping shoppingCartMapping;

    /**
     * 添加购物车方法
     *
     * @param shoppingCart 前端传来的购物车数据
     * @return 返回添加成功后的购物车数据
     */
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
     //1.判断当前加入的菜品或者套餐在当前用户的购物车数据记录中是否含有 这个数据
        ShoppingCart dbShoppingCart = shoppingCartMapping.findByShoppingCart(shoppingCart);
        if(dbShoppingCart !=null){
         dbShoppingCart.setNumber(dbShoppingCart.getNumber()+1);
            shoppingCartMapping.updateNumber(dbShoppingCart.getId(), dbShoppingCart.getNumber());
        }else{
            //如果没有 调用mapper 新增一条购物车记录数据
            dbShoppingCart = shoppingCart;
            dbShoppingCart.setCreateTime(LocalDateTime.now());
            dbShoppingCart.setNumber(1);
            //新增插入
            shoppingCartMapping.save(dbShoppingCart);
        }
        return dbShoppingCart;
    }

    @Override
    public R<ShoppingCart> subCart(ShoppingCart shoppingCart) {
        ShoppingCart dbshoppingCart = shoppingCartMapping.selectById(shoppingCart);
       Integer num= dbshoppingCart.getNumber() - 1;
        if(num==0){
           // shoppingCartMapping.updateNumber(dbshoppingCart.getId(), num);
            shoppingCartMapping.deleteByUidDid(shoppingCart);
            return R.success(new ShoppingCart());
        }
        shoppingCartMapping.updateNumber(dbshoppingCart.getId(), dbshoppingCart.getNumber()-1);
        dbshoppingCart = shoppingCartMapping.selectById(shoppingCart);
        return R.success(dbshoppingCart);
    }
    /**
     * 查询指定用户的购物车集合数据
     * @param userId 用户的id
     * @return 返回购物车集合的数据
     */
    @Override
    public List<ShoppingCart> findAllByUserId(Long userId) {
        return shoppingCartMapping.findAllByUserId(userId);
    }
    /**
     * 清空购物车
     * @param userId
     */
    @Override
    public void clean(Long userId) {
        shoppingCartMapping.deleteByUserId(userId);
    }

}
